package com.group.yqxxb.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group.yqxxb.pojo.*;
import com.group.yqxxb.service.MessageService;
import com.group.yqxxb.util.ApiResponseUtil;
import io.netty.handler.codec.base64.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    private static final Logger LOG = LoggerFactory.getLogger(MessageService.class);

    ApiResponseUtil apiResponseUtil = new ApiResponseUtil();
    @Override
    public JSONObject sendCommonMsg(Message message)throws Exception{
        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/msg/sendMsg.action");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("from", message.getFrom()));
        nvps.add(new BasicNameValuePair("ope", message.getOpe().toString()));
        nvps.add(new BasicNameValuePair("to", message.getTo()));
        nvps.add(new BasicNameValuePair("type", message.getType().toString()));
        nvps.add(new BasicNameValuePair("body", JSONObject.toJSONString(message.getBody())));
        nvps.add(new BasicNameValuePair("msgDesc", message.getMsgDesc()));
        if(!ObjectUtils.isEmpty(message.getAntispam())){
            nvps.add(new BasicNameValuePair("antispam", message.getAntispam().toString()));
        }
        nvps.add(new BasicNameValuePair("antispamCustom", message.getAntispamCustom()));
        nvps.add(new BasicNameValuePair("option", message.getOption()));
        nvps.add(new BasicNameValuePair("pushcontent", message.getPushcontent()));
        nvps.add(new BasicNameValuePair("payload", message.getPayload()));
        nvps.add(new BasicNameValuePair("ext", message.getExt()));
        nvps.add(new BasicNameValuePair("forcepushlist", message.getForcepushlist()));
        nvps.add(new BasicNameValuePair("forcepushcontent", message.getForcepushcontent()));
        nvps.add(new BasicNameValuePair("forcepushall", message.getForcepushall()));
        nvps.add(new BasicNameValuePair("bid", message.getBid()));
        if(!ObjectUtils.isEmpty(message.getUseYidun())){
            nvps.add(new BasicNameValuePair("useYidun", message.getUseYidun().toString()));
        }
        nvps.add(new BasicNameValuePair("yidunAntiCheating", message.getYidunAntiCheating()));
        if(!ObjectUtils.isEmpty(message.getMarkRead())){
            nvps.add(new BasicNameValuePair("markRead", message.getMarkRead().toString()));
        }
        if(!ObjectUtils.isEmpty(message.getCheckFriend())){
            nvps.add(new BasicNameValuePair("checkFriend", message.getCheckFriend().toString()));
        }
        if(!ObjectUtils.isEmpty(message.getSubType())){
            nvps.add(new BasicNameValuePair("subType", message.getSubType().toString()));
        }
        if(!ObjectUtils.isEmpty(message.getMsgSenderNoSense())){
            nvps.add(new BasicNameValuePair("msgSenderNoSense", message.getMsgSenderNoSense().toString()));
        }
        if(!ObjectUtils.isEmpty(message.getMsgReceiverNoSense())){
            nvps.add(new BasicNameValuePair("msgReceiverNoSense", message.getMsgReceiverNoSense().toString()));
        }
        nvps.add(new BasicNameValuePair("env", message.getEnv()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
        if(jsonObject.getInteger("code")==200){
            LOG.info("消息发送成功，消息内容:{"+JSONObject.toJSONString(message.getBody())+"}");
            LOG.info(message.getFrom()+"---》"+message.getTo());
        }else{
            LOG.error("消息发送失败，返回内容："+jsonObject);
        }
        return jsonObject;
    }


    /**
     * 批量发送单点消息
     * */
    @Override
    public JSONObject sendBatchMsg(SingleBatchMessage message) throws Exception{
        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/msg/sendBatchMsg.action");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        JSONArray jsonArray = new JSONArray();
        List<String> list =message.getToAccids();
        for (String x:list){
            /**
             * 构建json数组进行传参
             * */
            jsonArray.add(x);
        }
        nvps.add(new BasicNameValuePair("fromAccid", message.getFromAccid()));
        nvps.add(new BasicNameValuePair("toAccids", jsonArray.toString()));
        nvps.add(new BasicNameValuePair("type", message.getType().toString()));
        nvps.add(new BasicNameValuePair("body", JSONObject.toJSONString(message.getBody())));
        nvps.add(new BasicNameValuePair("msgDesc", message.getMsgDesc()));
        nvps.add(new BasicNameValuePair("option", message.getOption()));
        nvps.add(new BasicNameValuePair("pushcontent", message.getPushcontent()));
        nvps.add(new BasicNameValuePair("payload", message.getPayload()));
        nvps.add(new BasicNameValuePair("ext", message.getExt()));
        nvps.add(new BasicNameValuePair("bid", message.getBid()));
        if(!ObjectUtils.isEmpty(message.getUseYidun())){
            nvps.add(new BasicNameValuePair("useYidun", message.getUseYidun().toString()));
        }
        nvps.add(new BasicNameValuePair("env", message.getEnv()));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
        if(jsonObject.getInteger("code")==200){
            if(!ObjectUtils.isEmpty(jsonObject.getString("unregister"))){
                LOG.info("消息接口调用成功，但包含未注册用户："+jsonObject.getString("unregister"));
            }else{
                LOG.info("群发消息发送成功，消息内容:{"+JSONObject.toJSONString(message.getBody())+"}");
                LOG.info("发送者"+message.getFromAccid());
                LOG.info("发送账号组为："+jsonArray);
            }
            LOG.info("发送时间戳："+jsonObject.getString("timetag"));
        }else{
            LOG.error("消息发送失败，返回内容："+jsonObject);
        }
        return jsonObject;
    }


    /**
     * 用户撤回消息方法
     * 现在报 账号id不存在 待解决
     * */
    @Override
    public JSONObject recallMsg(RecallMessage message)throws Exception{
        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/msg/recall.action");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("deleteMsgid", message.getDeleteMsgid()));
        Long timetag = message.getTimetag();
        nvps.add(new BasicNameValuePair("timetag", timetag.toString()));
        nvps.add(new BasicNameValuePair("from", message.getFrom()));
        nvps.add(new BasicNameValuePair("to", message.getTo()));
        nvps.add(new BasicNameValuePair("type", message.getType().toString()));
        nvps.add(new BasicNameValuePair("msg", message.getMsg()));
        nvps.add(new BasicNameValuePair("ignoreTime", message.getIgnoreTime()));
        nvps.add(new BasicNameValuePair("pushcontent", message.getPushcontent()));
        nvps.add(new BasicNameValuePair("payload", message.getPayload()));
        nvps.add(new BasicNameValuePair("env", message.getEnv()));
        nvps.add(new BasicNameValuePair("attach", message.getAttach()));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
        if(jsonObject.getInteger("code")==200){
                LOG.info("撤回消息成功");
                LOG.info("撤回者"+message.getFrom());
                //LOG.info("撤回的内容："+message.get);
            LOG.info("撤回消息的时间戳："+jsonObject.getString("timetag"));
        }else{
            LOG.error("消息撤回失败，返回内容："+jsonObject);
        }
        return jsonObject;
    }

    /**
     * 单向删除消息
     * 现在报 账号id不存在 待解决
     * */
    @Override
    public JSONObject delMsgOneWay(RecallMessage message)throws Exception{
        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/msg/delMsgOneWay.action");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("deleteMsgid", message.getDeleteMsgid()));
        Long timetag = message.getTimetag();
        nvps.add(new BasicNameValuePair("timetag", timetag.toString()));
        nvps.add(new BasicNameValuePair("from", message.getFrom()));
        nvps.add(new BasicNameValuePair("to", message.getTo()));
        nvps.add(new BasicNameValuePair("type", message.getType().toString()));
        nvps.add(new BasicNameValuePair("msg", message.getMsg()));


        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
        if(jsonObject.getInteger("code")==200){
                LOG.info("删除消息成功");
                LOG.info("删除者"+message.getFrom());
                //LOG.info("撤回的内容："+message.get);
                LOG.info("删除消息的时间戳："+jsonObject.getString("timetag"));
        }else{
            LOG.error("消息删除失败，返回内容："+jsonObject);
        }
        return jsonObject;
    }


//    @Override
//    public JSONObject uploadMessage(UploadFile file)throws Exception{
//        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/msg/upload.action");
//        // 设置请求的参数
//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//
//        BASE64Encoder base64Encoder =new BASE64Encoder();
//        String base64EncoderImg = file.getContent().getOriginalFilename()+","+ base64Encoder.encode(file.getContent().getBytes());
//        System.out.println(base64EncoderImg);
//        //Base64.encode(file.getContent().getBytes());
//        nvps.add(new BasicNameValuePair("content", base64EncoderImg));
//        nvps.add(new BasicNameValuePair("type", file.getType()));
//        nvps.add(new BasicNameValuePair("ishttps", file.getIshttps()));
//        nvps.add(new BasicNameValuePair("expireSec", file.getExpireSec().toString()));
//        nvps.add(new BasicNameValuePair("tag", file.getTag()));
//
//
//        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
//        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
//        if(jsonObject.getInteger("code")==200){
//            LOG.info("上传文件成功");
//        }else{
//            LOG.error("上传文件失败，返回内容："+jsonObject);
//        }
//        return jsonObject;
//    }


    /**
     * 返回历史发出消息的方法
     * */
    @Override
    public List<AgoMessage> getAgoMessages(AgoMessageRequest agoMessageRequest)throws Exception{
        HttpPost httpPost =  apiResponseUtil.buildHeader("https://api.netease.im/nimserver/history/querySessionMsg.action");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("limit", agoMessageRequest.getLimit().toString()));
        nvps.add(new BasicNameValuePair("from", agoMessageRequest.getFrom()));
        nvps.add(new BasicNameValuePair("to", agoMessageRequest.getTo()));
        nvps.add(new BasicNameValuePair("begintime", agoMessageRequest.getBegintime()));
        nvps.add(new BasicNameValuePair("endtime", agoMessageRequest.getEndtime()));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        JSONObject jsonObject = apiResponseUtil.returnJSON(httpPost);
        List<AgoMessage> list = new ArrayList<>();

        if(jsonObject.getInteger("code")==200){
            for (Object jsonObject1:jsonObject.getJSONArray("msgs")){
                JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.toString());
                AgoMessage agoMessage = JSON.parseObject(String.valueOf(jsonObject2),AgoMessage.class);
                list.add(agoMessage);
            }
            LOG.info("获取历史消息列表成功，from:{"+agoMessageRequest.getFrom()+"} to:{"+agoMessageRequest.getTo()+"}");
        }else{
            LOG.error("获取历史消息记录失败，返回内容："+jsonObject);
            return null;
        }
        return list;
    }
}
